package com.xopencode.io;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Mcb
 * @date 2022/5/3
 * @apiNote 使用nio进行文件复制
 */
public class CopyTest {
    public static void main(String[] args) throws IOException {
        File file = new File("test.jpg");
        File fileCopy = new File("Copy.jpg");

        FileInputStream inputStream = new FileInputStream(file);
        FileChannel channel = inputStream.getChannel();

        FileOutputStream outputStream = new FileOutputStream(fileCopy);
        FileChannel copyChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true){
            buffer.clear(); //重复读取需要position归零
            int read = channel.read(buffer);
            System.out.println("读取字段数："+read);
            if (read == -1){
                break;
            }
            buffer.flip();
            copyChannel.write(buffer);
        }
        System.out.println("复制成功");
        copyChannel.close();
        channel.close();
        inputStream.close();
        outputStream.close();
    }
}
